"""
自定义权限类
"""
from rest_framework import permissions
from .models import RolePermission


class IsAdminUser(permissions.BasePermission):
    """管理员权限"""
    
    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated and request.user.is_admin


class IsTeacherOrAdmin(permissions.BasePermission):
    """老师或管理员权限"""
    
    def has_permission(self, request, view):
        return (request.user and request.user.is_authenticated and 
                (request.user.is_teacher or request.user.is_admin))


class IsStudentUser(permissions.BasePermission):
    """学生权限"""
    
    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated and request.user.is_student


class HasPermission(permissions.BasePermission):
    """基于权限代码的权限检查"""
    
    def __init__(self, permission_codename):
        self.permission_codename = permission_codename
    
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        
        # 管理员拥有所有权限
        if request.user.is_admin:
            return True
        
        # 检查用户角色是否有该权限
        return RolePermission.objects.filter(
            role=request.user.role,
            permission__codename=self.permission_codename
        ).exists()


class IsOwnerOrReadOnly(permissions.BasePermission):
    """对象所有者或只读权限"""
    
    def has_object_permission(self, request, view, obj):
        # 读权限允许任何请求
        if request.method in permissions.SAFE_METHODS:
            return True
        
        # 写权限只给对象所有者
        return obj.user == request.user or request.user.is_admin


class IsOwner(permissions.BasePermission):
    """对象所有者权限"""
    
    def has_object_permission(self, request, view, obj):
        return obj.user == request.user or request.user.is_admin
